/**
 * 食物API模拟服务
 * 当后端API不可用或返回错误时，可以使用此模拟服务提供测试数据
 */

// 模拟的食物分类数据
const foodCategories = [
  { id: '60a3b4e8f5f6f30b4c7a8b7f', name: '水果', icon: 'fas fa-apple-alt', iconColor: 'text-red-500' },
  { id: 'category_grains_id', name: '谷物类', icon: 'fas fa-bread-slice', iconColor: 'text-amber-500' },
  { id: 'category_veg_id', name: '蔬菜类', icon: 'fas fa-carrot', iconColor: 'text-orange-500' },
  { id: 'category_meat_id', name: '肉类', icon: 'fas fa-drumstick-bite', iconColor: 'text-rose-500' },
];

// 模拟的食物数据
const mockFoods = [
  {
    _id: '1',
    name: '苹果',
    category: { id: '60a3b4e8f5f6f30b4c7a8b7f', name: '水果' },
    image: 'https://via.placeholder.com/300x200.png?text=Apple',
    unit: '100克',
    calories: 52,
    nutrition: {
      protein: 0.3,
      fat: 0.2,
      carbohydrate: 13.8,
      fiber: 2.4
    },
    isVerified: true,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  },
  {
    _id: '2',
    name: '香蕉',
    category: { id: '60a3b4e8f5f6f30b4c7a8b7f', name: '水果' },
    image: 'https://via.placeholder.com/300x200.png?text=Banana',
    unit: '100克',
    calories: 89,
    nutrition: {
      protein: 1.1,
      fat: 0.3,
      carbohydrate: 22.8,
      fiber: 2.6
    },
    isVerified: true,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  },
  {
    _id: '3',
    name: '米饭',
    category: { id: 'category_grains_id', name: '谷物类' },
    image: 'https://via.placeholder.com/300x200.png?text=Rice',
    unit: '100克',
    calories: 130,
    nutrition: {
      protein: 2.7,
      fat: 0.3,
      carbohydrate: 28.2,
      fiber: 0.4
    },
    isVerified: true,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  },
  {
    _id: '4',
    name: '胡萝卜',
    category: { id: 'category_veg_id', name: '蔬菜类' },
    image: 'https://via.placeholder.com/300x200.png?text=Carrot',
    unit: '100克',
    calories: 41,
    nutrition: {
      protein: 0.9,
      fat: 0.2,
      carbohydrate: 9.6,
      fiber: 2.8
    },
    isVerified: true,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  },
];

/**
 * 模拟搜索食物API
 * @param {Object} params 查询参数
 * @returns {Promise<Object>} 模拟的API响应
 */
export function mockSearchFoods(params) {
  return new Promise(resolve => {
    console.log('[Mock API] 接收到搜索食物请求:', params);
    
    // 延迟500ms模拟网络请求
    setTimeout(() => {
      try {
        // 过滤和分页逻辑
        let filteredFoods = [...mockFoods];
        
        // 按名称过滤
        if (params.name) {
          const searchTerm = params.name.toLowerCase();
          filteredFoods = filteredFoods.filter(food => 
            food.name.toLowerCase().includes(searchTerm)
          );
        }
        
        // 按分类过滤
        if (params.categoryId && params.categoryId !== 'all') {
          filteredFoods = filteredFoods.filter(food => 
            food.category.id === params.categoryId
          );
        }
        
        // 按验证状态过滤
        if (params.isVerified !== undefined) {
          filteredFoods = filteredFoods.filter(food => 
            food.isVerified === params.isVerified
          );
        }
        
        // 计算分页
        const page = params.page || 1;
        const limit = params.limit || 10;
        const total = filteredFoods.length;
        const totalPages = Math.ceil(total / limit);
        const startIndex = (page - 1) * limit;
        const endIndex = startIndex + limit;
        const paginatedFoods = filteredFoods.slice(startIndex, endIndex);
        
        // 返回结果
        const result = {
          error: 0,
          message: '获取食物列表成功',
          body: {
            foods: paginatedFoods,
            total,
            totalPages,
            currentPage: page
          }
        };
        
        console.log('[Mock API] 返回搜索结果:', {
          totalCount: total,
          returnedCount: paginatedFoods.length,
          page,
          totalPages
        });
        
        resolve(result);
      } catch (error) {
        console.error('[Mock API] 处理请求时出错:', error);
        resolve({
          error: 1,
          message: '服务器内部错误',
          body: null
        });
      }
    }, 500);
  });
}

/**
 * 模拟获取食物详情API
 * @param {string} foodId 食物ID
 * @returns {Promise<Object>} 模拟的API响应
 */
export function mockGetFoodDetail(foodId) {
  return new Promise(resolve => {
    console.log('[Mock API] 接收到获取食物详情请求:', foodId);
    
    // 延迟300ms模拟网络请求
    setTimeout(() => {
      const food = mockFoods.find(f => f._id === foodId);
      
      if (food) {
        // 对于详情，我们扁平化nutrition字段与主对象
        const foodDetail = {
          ...food,
          protein: food.nutrition.protein,
          fat: food.nutrition.fat,
          carbohydrate: food.nutrition.carbohydrate,
          fiber: food.nutrition.fiber
        };
        
        resolve({
          error: 0,
          message: '获取食物详情成功',
          body: foodDetail
        });
      } else {
        resolve({
          error: 1,
          message: '食物不存在',
          body: null
        });
      }
    }, 300);
  });
}

/**
 * 模拟食物图片URL助手
 * @param {string} imagePath 图片路径
 * @returns {string} 完整图片URL
 */
export function mockGetFullFoodImageUrl(imagePath) {
  if (!imagePath) return 'https://via.placeholder.com/300x200.png?text=No+Image';
  return imagePath;
}

export default {
  mockSearchFoods,
  mockGetFoodDetail,
  mockGetFullFoodImageUrl
}; 